package com.ruoyi.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.PasswordBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.WebLoginService;
import com.ruoyi.system.service.IShopCompanyInfoService;
import com.ruoyi.system.service.IShopLicenceInfoService;
import com.ruoyi.system.service.IShopUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class iShopUserLoginController extends BaseController
{
    @Autowired
    private WebLoginService webLoginService;
    @Autowired
    private IShopLicenceInfoService shopLicenceInfoService;
    @Autowired
    private IShopCompanyInfoService shopCompanyInfoService;
    @Autowired
    private IShopUserService shopUserService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysLoginService loginService;

    /**
     * web端用户登录：手机号、密码、图形验证码
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        //验证码检查
        ShopUser userInfo = webLoginService.validateCaptcha(loginBody.getUsername(), loginBody.getPassword(),loginBody.getCode(),loginBody.getUuid());
        // 返回企业名称
        if(userInfo.getUserType() != null && "0".equals(userInfo.getUserType())) {
            ShopCompanyInfo shopCompanyInfo = shopCompanyInfoService.selectShopCompanyInfoByCompanyId(userInfo.getCompanyId());
            userInfo.setCompanyName(shopCompanyInfo.getCompanyName());
        }
        //生成token
        StpUtil.login(userInfo.getUserId());
        //登录信息存到redis
        redisCache.setCacheObject(StpUtil.getTokenValue(),userInfo);

        return AjaxResult.success(AjaxResult.LOGIN_SUCCESS_MSG,new LoginResponse(userInfo, StpUtil.getTokenValue()));

    }

    /**
     * web企业认证
     */
    @PostMapping("/companyCertification")
    public AjaxResult companyCertification(@RequestBody LoginBody loginBody)
    {
        //验证码检查
        ShopUser userInfo = webLoginService.validateCaptcha(loginBody.getUsername(), loginBody.getPassword(),loginBody.getCode(),loginBody.getUuid());
        // 返回企业名称
        if(userInfo.getUserType() != null && "0".equals(userInfo.getUserType())) {
            ShopCompanyInfo shopCompanyInfo = shopCompanyInfoService.selectShopCompanyInfoByCompanyId(userInfo.getCompanyId());
            userInfo.setCompanyName(shopCompanyInfo.getCompanyName());
        }
        //生成token
        StpUtil.login(userInfo.getUserId());
        //登录信息存到redis
        redisCache.setCacheObject(StpUtil.getTokenValue(),userInfo);

        return AjaxResult.success(AjaxResult.LOGIN_SUCCESS_MSG,new LoginResponse(userInfo, StpUtil.getTokenValue()));

    }

    //注册交易
    @PostMapping("/register")
    public Map register(@RequestBody WebRegisterBody registerBody)
    {
        //判断账号是否存在
        if(shopUserService.selectShopUserByUserName(registerBody.getUserName())!=null){
            throw new ServiceException("用户账号已存在");
        }
        ShopLicenceInfo shopLicenceInfo = new ShopLicenceInfo();
        shopLicenceInfo.setLicenceName(registerBody.getCompanyName());
        shopLicenceInfo.setLicenceUrl(registerBody.getLicenceUrl());
        shopLicenceInfo.setLicenceNum(registerBody.getLicenceNum());
        //其他值完善下
        //营业执照信息插入
        shopLicenceInfoService.insertShopLicenceInfo(shopLicenceInfo);
        //联系人新增
        ShopUser shopUser = new ShopUser();
        shopUser.setNickName(registerBody.getNickName());
        shopUser.setCompanyName(registerBody.getCompanyName());
        shopUser.setUserName(registerBody.getUserName());
        shopUser.setPassword(registerBody.getPassword());
        shopUser.setEmail(registerBody.getEmail());


        //公司信息插入
        String uuid = IdUtils.simpleUUID();
        ShopCompanyInfo shopCompanyInfo = new ShopCompanyInfo();
        shopCompanyInfo.setCompanyName(registerBody.getCompanyName());
        shopCompanyInfo.setCompanyUrl(registerBody.getCompanyUrl());
        shopCompanyInfo.setLicenceNum(registerBody.getLicenceNum());
        shopCompanyInfo.setProvince(registerBody.getProvince());
        shopCompanyInfo.setCity(registerBody.getCity());
        shopCompanyInfo.setArea(registerBody.getArea());
        shopCompanyInfo.setCompanyAddress(registerBody.getCompanyAddress());
        shopCompanyInfo.setCompanyInfo(registerBody.getCompanyInfo());
        shopCompanyInfo.setRemark(uuid);
        shopCompanyInfo.setLicenceId(shopLicenceInfo.getLicenceId());
        shopCompanyInfo.setContactName(registerBody.getNickName());
        shopCompanyInfo.setContactTel(registerBody.getUserName());

        shopCompanyInfoService.insertShopCompanyInfo(shopCompanyInfo);
        shopUser.setCompanyId(shopCompanyInfo.getCompanyId());
        shopUser.setUserType("0");
        shopUserService.insertShopUser(shopUser);
        //生成token
        StpUtil.login(shopUser.getUserId());
        //登录信息存到redis
        redisCache.setCacheObject(StpUtil.getTokenValue(),shopUser);
        return AjaxResult.success(AjaxResult.LOGIN_SUCCESS_MSG,new LoginResponse(shopUser, StpUtil.getTokenValue()));

    }


   //个人用户注册
   @PostMapping("/personRegister")
   public AjaxResult personRegister(@RequestBody ShopUser shopUser)
   {
       AjaxResult ajax = AjaxResult.success();
       //判断账号是否存在
       if(shopUserService.selectShopUserByUserName(shopUser.getUserName())!=null){
           throw new ServiceException("用户账号已存在");
       }
       //检查验证码
       String code = shopUser.getCode();
       String codeRedis = redisCache.getCacheObject("sms"+shopUser.getUserName());
       if(shopUser.getUserName().isEmpty()){
           throw new ServiceException("手机号不能为空");
       }
       if(code.isEmpty()){
           throw new ServiceException("验证码不能为空");
       }
    /*   if(codeRedis.isEmpty()){
           throw new ServiceException("验证码超时或者不存在");
       }*/
      /* if(!code.equals(codeRedis)){
           throw new ServiceException("验证码不正确");
       }*/
       shopUserService.insertShopUser(shopUser);
       //生成token
       StpUtil.login(shopUser.getUserId());
       redisCache.setCacheObject(StpUtil.getTokenValue(),shopUser);
       return AjaxResult.success(AjaxResult.LOGIN_SUCCESS_MSG,new LoginResponse(shopUser, StpUtil.getTokenValue()));
   }

    //获取字典数据
    @GetMapping("/getDictData")
    public AjaxResult getDictData(String dictName)
    {
        String[] dicts = dictName.split(",");
        Map<String,Object> map = new HashMap<>();
        for (String dictKey:dicts){
            map.put(dictKey, DictUtils.getDictCache(dictKey));
        }
        return AjaxResult.success(map);

    }


    //修改密码
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody PasswordBody passwordBody)
    {

        Object loginId = StpUtil.getLoginId();
        long id = Long.parseLong((String) loginId);
        ShopUser shopUser = shopUserService.selectShopUserByUserId(id);
        if(!shopUser.getPassword().equals(passwordBody.getOldPassword())){
            throw new ServiceException("旧密码不正确");
        }
        if (!passwordBody.getNewPassword().equals(passwordBody.getConfirmPassword())){
            throw new ServiceException("新密码与确认密码不一致");
        }
        if (passwordBody.getNewPassword().equals(passwordBody.getOldPassword())){
            throw new ServiceException("新密码不能与旧密码相同");
        }
        shopUser.setPassword(passwordBody.getNewPassword());
        shopUserService.updateShopUser(shopUser);
        return AjaxResult.success();
    }

    //忘记密码
    @PostMapping("/forgetPassword")
    public AjaxResult forgetPassword(@RequestBody LoginBody loginBody)
    {
        ShopUser shopUser = shopUserService.selectShopUserByUserName(loginBody.getUsername());
        if(shopUser==null){
            throw new ServiceException("用户不存在");
        }
        //验证码验证
        String redisCode = redisCache.getCacheObject("sms" + loginBody.getUsername());
        if(!loginBody.getCode().equals(redisCode)){
            throw new ServiceException("验证码不正确");
        }
        //新密码
        if (loginBody.getPassword()==null){
            throw new ServiceException("新密码不能为空");
        }
        if (shopUser.getPassword().equals(loginBody.getPassword())){
            throw new ServiceException("新密码不能与旧密码相同");
        }

        shopUser.setPassword(loginBody.getPassword());
        shopUserService.updateShopUser(shopUser);
        return AjaxResult.success();
    }


}
